package cn.fl.mcr.controller;

import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import cn.cmm.base.framework.utils.CollectionUtils;
import cn.fl.mcr.service.IMcrCrTypCloseService;
import cn.fl.mcr.transform.McrCityOpenCtrlVOTransform;
import cn.fl.mcr.vo.McrCityOpenCtrlVO;
import cn.fl.mcr.vo.McrCrTypCloseVO;
import cn.lionbridgecapital.loan.model.base.Pager;
import cn.lionbridgecapital.loan.model.condition.McrCityOpenCtrlQC;
import cn.lionbridgecapital.loan.model.condition.McrCrTypCloseQC;
import cn.lionbridgecapital.loan.model.dto.McrCityOpenCtrlDTO;
import cn.lionbridgecapital.loan.model.po.McrCrTypClose;
import cn.lionbridgecapital.loan.service.api.IMcrCityOpenCtrlApiService;
import cn.lionbridgecapital.loan.service.api.IMcrCrTypCloseApiService;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;

import cn.fl.framework.base.context.CurrentThreadContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.fl.system.constant.SysLogConstant;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.StringUtils;

/**
 * @Description:  控制层
 */
@Controller
@RequestMapping("/mcr/mcrCrTypClose")
public class McrCrTypCloseController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(McrCrTypCloseController.class);

	/**
	 * McrCrTypClose 服务层BEAN
	 */
	@Autowired
	private IMcrCrTypCloseService mcrCrTypCloseService;
	@Autowired
	private IMcrCityOpenCtrlApiService mcrCityOpenCtrlApiService;

	@Autowired
	private IMcrCrTypCloseApiService mcrCrTypCloseApiService;

	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("mcr/mcrCrTypClose/mcrCrTypCloseList");
		McrCityOpenCtrlQC qc = new McrCityOpenCtrlQC();
		qc.setIsValid(BaseConstant.IS_YESNO_YES);
		qc.setIsDel(BaseConstant.IS_YESNO_NO);
		/*List<McrCityOpenCtrlVO> ctrlList = McrCityOpenCtrlVOTransform.toVOList(mcrCityOpenCtrlApiService.searchMcrCityOpenCtrlDTOList(qc));
		view.addObject("ctrlList", ctrlList);*/
		BaseLogUtils.info(logger, "toListPage", "跳转到列表页面.", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 到修改页面
	 */
	@RequestMapping(value = "/toAddPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		ModelAndView view = new ModelAndView("mcr/mcrCrTypClose/mcrCrTypCloseAdd");
		view.addObject("id", id);
		McrCityOpenCtrlQC qc = new McrCityOpenCtrlQC();
		qc.setIsValid(BaseConstant.IS_YESNO_YES);
		qc.setIsDel(BaseConstant.IS_YESNO_NO);
		List<McrCityOpenCtrlVO> ctrlList = McrCityOpenCtrlVOTransform.toVOList(mcrCityOpenCtrlApiService.searchMcrCityOpenCtrlDTOList(qc));
		McrCityOpenCtrlVO vo =new McrCityOpenCtrlVO();
		vo.setCityCode("1111");
		vo.setCityName("全部");
		ctrlList.add(0,vo);

		McrCrTypCloseVO mcrCrTypCloseVO = new McrCrTypCloseVO();
		List<Map<String,String>> crPdList = mcrCrTypCloseVO.getCrPdList();
		view.addObject("ctrlList", JSON.toJSONString(ctrlList));
		view.addObject("crPdList", JSON.toJSONString(crPdList));
		BaseLogUtils.info(logger, "toModifyPage", "跳转到修改页面.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do")
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response, McrCrTypCloseQC qc) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		page.setCondition(qc);

		Pager pager = this.mcrCrTypCloseService.searchListPage(page);
		List<McrCrTypCloseVO> list = (List<McrCrTypCloseVO>) pager.getResultList();
		ListPageVO<McrCrTypCloseVO> listPage = new ListPageVO<McrCrTypCloseVO>(list, pager.getTotalCount());
		BaseLogUtils.info(logger, "initList", "查询数据完成. DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeById.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		try {
			this.mcrCrTypCloseService.removeById(Long.valueOf(id));
			BaseLogUtils.info(logger, "removeById", "删除数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.error(logger, "getById", "获取数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		try {
			McrCrTypCloseVO vo = this.mcrCrTypCloseService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getById", "获取数据,数据不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			}
			result.setData(vo);
			BaseLogUtils.info(logger, "getById", "获取数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response, McrCrTypCloseVO entity) throws BaseException {
		String name = request.getParameter("name");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		try {
			String cityCode = request.getParameter("cityCode");
			if(StringUtils.isNotEmpty(cityCode)){
				entity.setCityCodeClose(cityCode);
			}
			String cityCodeNm = request.getParameter("cityCodeNm");
			if(StringUtils.isNotEmpty(cityCodeNm)){
				entity.setCityCode(cityCodeNm);
			}
			String crPdOpt = request.getParameter("crPdOpt");
			if(StringUtils.isNotEmpty(crPdOpt)){
				entity.setCrPdOpt(crPdOpt);
			}
			List<String> cityCodeList = Arrays.asList(cityCodeNm.split(";"));
			McrCityOpenCtrlQC mcrCityOpenCtrlQC = new McrCityOpenCtrlQC();
			mcrCityOpenCtrlQC.setIsDel(BaseConstant.IS_YESNO_NO);
			mcrCityOpenCtrlQC.setIsValid(BaseConstant.IS_YESNO_YES);
			mcrCityOpenCtrlQC.setCityCodeList(cityCodeList);
			if(cityCodeList.contains("1111")){
                entity.setCityCodeName("全部");
            }
			List<McrCityOpenCtrlDTO> mcrCityOpenCtrlDTOS = mcrCityOpenCtrlApiService.searchMcrCityOpenCtrlDTOList(mcrCityOpenCtrlQC);
			BaseLogUtils.info(logger, "initList", "贷款类型开关.查询城市编码映射. DATA:" + JSONObject.toJSONString(mcrCityOpenCtrlDTOS), CurrentThreadContext.getCurrentUserName());
			if(CollectionUtils.isNotEmpty(mcrCityOpenCtrlDTOS)){
				for (McrCityOpenCtrlDTO dto : mcrCityOpenCtrlDTOS) {
					entity.setCityCodeName(StringUtils.isEmpty(entity.getCityCodeName())?dto.getCityName():entity.getCityCodeName()+";"+dto.getCityName());
				}
			}
			entity.setCrtTm(new Date());
			entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
			Long id = this.mcrCrTypCloseService.add(entity);
			result.setData(id);
			BaseLogUtils.info(logger, "add", "新增数据.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modify(HttpServletRequest request, HttpServletResponse response, McrCrTypCloseVO entity) throws BaseException {
		String id = request.getParameter("id");
		String name = request.getParameter("name");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "modify", "修改数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		try {
			String cityCode = request.getParameter("cityCode");
			if(StringUtils.isNotEmpty(cityCode)){
				entity.setCityCodeClose(cityCode);
			}
			String cityCodeNm = request.getParameter("cityCodeNm");
			if(StringUtils.isNotEmpty(cityCodeNm)){
				entity.setCityCode(cityCodeNm);
				List<String> cityCodeList = Arrays.asList(cityCodeNm.split(";"));
				McrCityOpenCtrlQC mcrCityOpenCtrlQC = new McrCityOpenCtrlQC();
				mcrCityOpenCtrlQC.setIsDel(BaseConstant.IS_YESNO_NO);
				mcrCityOpenCtrlQC.setIsValid(BaseConstant.IS_YESNO_YES);
				mcrCityOpenCtrlQC.setCityCodeList(cityCodeList);
				if(cityCodeList.contains("1111")){
					entity.setCityCodeName("全部");
				}
				List<McrCityOpenCtrlDTO> mcrCityOpenCtrlDTOS = mcrCityOpenCtrlApiService.searchMcrCityOpenCtrlDTOList(mcrCityOpenCtrlQC);
				BaseLogUtils.info(logger, "initList", "贷款类型开关.查询城市编码映射. DATA:" + JSONObject.toJSONString(mcrCityOpenCtrlDTOS), CurrentThreadContext.getCurrentUserName());
				if(CollectionUtils.isNotEmpty(mcrCityOpenCtrlDTOS)){
					for (McrCityOpenCtrlDTO dto : mcrCityOpenCtrlDTOS) {
						entity.setCityCodeName(StringUtils.isEmpty(entity.getCityCodeName())?dto.getCityName():entity.getCityCodeName()+";"+dto.getCityName());
					}
				}
			}
			entity.setId(Long.valueOf(id));
			entity.setMdfTm(new Date());
			entity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
			boolean success = this.mcrCrTypCloseService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
				BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "modify", "修改成功.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
}

